import socket
import threading
from PyQt5.QtWidgets import *  # type: ignore
from PyQt5.QtCore import *  # type: ignore
from PyQt5.QtGui import *  # type: ignore
import sys

from ui.Ui_main_window import Ui_MainWindow
from common import utils


class MianWindow(QMainWindow):
    #定义信号
    #参数1：0需要更新状态，1收到消息了
    #参数2：s数据
    msg_recv_signal = pyqtSignal(int, object)
    
    def __init__(self):
        super().__init__()
        # 创建对象
        self.ui = Ui_MainWindow()
        # 初始化内容
        self.ui.setupUi(self)
        # tcp客户端socket对象
        self.tcp_client: socket.socket = None  # type: ignore
        
        self.msg_recv_signal.connect(self.on_data_recv_slot)
        # 初始化ui
        self.init_ui()

    def update_connect_state(self):
        if self.tcp_client == None:
            self.ui.btn_connect.setText("连接网络")
            self.ui.btn_connect.setIcon(QIcon(":/ic/disconnect"))
        else:
            self.ui.btn_connect.setText("断开连接")
            self.ui.btn_connect.setIcon(QIcon(":/ic/connected"))
            
    #定义槽函数
    @pyqtSlot(str)
    def on_data_recv_slot(self,type_t, msg):
        if type_t == 0:
            self.update_connect_state()
        elif type_t == 1:
            self.ui.edit_recv.appendPlainText(msg)

    def run_tcp_client(self, target_ip, target_part):
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.tcp_client.connect((target_ip, int(target_part)))
        except Exception as e:
            print("连接服务器失败,请重试")
            return
 
        self.msg_recv_signal.emit(0, None)

        local_ip, local_part = self.tcp_client.getsockname()

        print(f"服务器连接成功, 本机信息:ip:{local_ip}, part:{local_part}")
        try:
            while True:
                bytes_data = self.tcp_client.recv(1024)
                if bytes_data:
                    msg = utils.decode_data(bytes_data)
                    print("收到数据:", msg)
                    # 
                    self.msg_recv_signal.emit(1, msg)
                else:
                    print("服务器已断开")
                    break
        except:
            print("客户端断开连接")
        if self.tcp_client is not None:
            self.tcp_client.close()
            self.tcp_client = None  # type: ignore
            
        self.update_connect_state()

    @pyqtSlot()
    def on_btn_connect_clicked(self):
        if self.tcp_client != None:
            self.tcp_client.close()
            self.tcp_client = None  # type: ignore
            return

        """连接服务器
        1.获取用户输入的IP和端口号
        2.创建子线程
        3.创建socket对象并连接服务器
        4.循环数据获取
        """
        target_ip = self.ui.edit_target_ip.text()
        target_part = self.ui.edit_target_port.text()
        mode = self.ui.cb_mode.currentText()
        # 创建子线程，允许socket数据接收任务
        t1 = threading.Thread(
            target=self.run_tcp_client, args=(target_ip, target_part), daemon=True
        )
        t1.start()

    @pyqtSlot()
    def on_btn_send_clicked(self):
        text = self.ui.edit_send.toPlainText()
        if len(text) == 0:
            self.statusBar().showMessage("请输入内容再发送", 1000)
            return

        if self.tcp_client == None:
            self.statusBar().showMessage("请先连接服务器再发送", 1000)
            QMessageBox.warning(self, "发送失败", "请先连接服务器")
            return

        self.tcp_client.send(text.encode())

    def init_ui(self):
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8080")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MianWindow()
    window.show()
    sys.exit(app.exec_())
